﻿using System;

namespace NMapper.Tests
{
    public static class AssertExtensions
    {
        public static void AssertTrue(this bool actual)
        {
            if (!actual)
                throw new Exception("Assertion failed");
        }

        public static void AssertTrue<T>(this T target, Func<T, bool> predicate)
        {
            if (!predicate(target))
                throw new Exception("Assertion failed");
        }

        public static void AssertFalse(this bool actual)
        {
            if (actual)
                throw new Exception("Assertion failed");
        }

        public static void AssertNotNull<T>(this T actual) where T : class
        {
            if (actual == null)
                throw new Exception("Assertion failed");
        }

        public static void AssertNotNull<T>(this T? actual) where T : struct
        {
            if (actual == null)
                throw new Exception("Assertion failed");
        }

        public static void AssertNull<T>(this T actual) where T : class
        {
            if (actual != null)
                throw new Exception("Assertion failed");
        }

        public static void AssertEquals<T>(this T actual, T expected)
        {
            AssertEquals(actual, expected, string.Format("Assertion (equals) failed.  Expected: {0}, Found: {1}", expected, actual));
        }

        public static void AssertEquals<T>(this T actual, T expected, string message)
        {
            bool result = actual.SafeEquals(expected);
            if (!result)
                throw new Exception(message);
        }
        
        private static bool SafeEquals<T>(this T o1, T o2)
        {
            bool o1Null = o1 == null;//EqualityComparer<T>.Default.Equals(o1, default(T));
            bool o2Null = o2 == null;//EqualityComparer<T>.Default.Equals(o2, default(T));
            if (o1Null && o2Null)
                return true;
            if (o1Null)
                return false;

            return o1.Equals(o2);
        }
        
        public static void AssertNotEquals<T>(this T actual, T expected)
        {
            AssertNotEquals(actual, expected, string.Format("Assertion (not equals) failed.  Expected: {0}, Found: {1}", expected, actual));
        }

        public static void AssertNotEquals<T>(this T actual, T expected, string message)
        {
            bool result = actual.SafeEquals(expected);
            if (result)
                throw new Exception(message);
        }
    }
}